<template>
  <el-row class="user-info-form" type="flex" justify="center">
    <el-col>
      <div class="asset-info-form">
        <el-form label-width="150px" :model="gridBaseInfoForm" :rules="gridBaseInfoFormRules" ref="gridBaseInfoForm" @submit.native.prevent>
          <el-form-item label="网格名称：" prop='gridName'>
            <el-input
              v-model="gridBaseInfoForm.gridName"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="所属行政区："  prop='areaName'>
            <el-select v-model="gridBaseInfoForm.areaName" filterable @change="selectAreaList">
              <el-option
                v-for="item in areaList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="网格负责人："  prop='chargeGridman'>
            <el-input
              v-model="gridBaseInfoForm.chargeGridman"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="网格负责人电话："  prop='chargeTel'>
            <el-input
              v-model="gridBaseInfoForm.chargeTel"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="网格员数量："  prop='gridmanCount'>
            <el-input
              v-model="gridBaseInfoForm.gridmanCount"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="图片：" prop='pictures'>
            <el-upload
              :action="QINIUUPLOADURL"
              :multiple="false"
              ref="upload"
              list-type="picture-card"
              :data="qiniuData"
              :on-success="handleAvatarSuccess"
              :on-remove="handleRemovePic"
              :on-error="handleError"
              :before-upload="beforeAvatarUpload"
              :on-preview="$imgPreview"
              :file-list="qiniuData.fileList"
              :limit="1"
              :on-exceed="handleExceed"
              accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label-width="0" class="verifyidentity-button">
            <el-button @click.stop="closeFun(false)" round>取消</el-button>
            <el-button type="primary" @click="saveGridInfo('gridBaseInfoForm')" round>保存</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-col>
  </el-row>
</template>
<script>
import { qnToken} from '@/api/api'
import util from '@/utils/util'
import { getListAreaCountySet, updateGridInfo } from '@/api/sysConfig'

export default {
    name: 'GridManageBaseInfo',
    props: {
      gridInfo: {
        type: Object
      },
      closeFun: {
        type: Function,
        required: true
      },
    },
    data(){
      return {
        areaList: [],
        qiniuData:{//上传图片携带的参数
          token : "",
          key : "",
          fileList:[],
        },
        // 表单数据
        gridBaseInfoForm: {
          id: '',
          gridName: '',
          areaName: '',
          chargeGridman: '',
          chargeTel: '',
          gridmanCount: '',
          belongId: ''
        },
        // 表单校验
        gridBaseInfoFormRules: {
          gridName: [
            { required: true, message: '请输入网格名称', trigger: 'change' }
          ],
          areaName: [
            { required: true, message: '请选择所属行政区', trigger: 'change' }
          ],
          chargeGridman: [
            { required: true, message: '请输入网格负责人', trigger: 'change' }
          ],
          chargeTel: [
            { required: true, message: '请输入网格负责人电话', trigger: 'change' },
            { required: true, message: '请输入正确手机号码！', trigger: 'blur', pattern: /^1[3456789]\d{9}$/}
          ],
          gridmanCount: [
            { required: true, message: '请输入网格员数量', trigger: 'change' },
            { pattern: /^[0-9]*[1-9][0-9]*$/, message: '必须为数字', trigger: 'blur' }
          ]
        }
      }
    },
    created() {
      let that = this
      that.getToken()
      // 获取业主单位信息
      getListAreaCountySet({
          queryType: 0,
          name: "",
          pageSize: 10,
          pageIndex: 0
      }).then(res => {
        if(res.status = 200) {
          that.areaList = res.data
        }
      })
      // 如果有历史值，设置回显
      if(that.gridInfo.id) {
        that.gridBaseInfoForm.id =  that.gridInfo.id
        that.gridBaseInfoForm.gridName = that.gridInfo.gridName
        that.gridBaseInfoForm.areaName = that.gridInfo.areaName
        that.gridBaseInfoForm.chargeGridman = that.gridInfo.chargeGridman
        that.gridBaseInfoForm.chargeTel = that.gridInfo.chargeTel
        that.gridBaseInfoForm.gridmanCount = that.gridInfo.gridmanCount
        that.gridBaseInfoForm.belongId = that.gridInfo.belongId
        // 设置上传图片初始值
        that.gridInfo.picUrl ? $.each(that.gridInfo.picUrl.split(','), (index,url) => {
          that.qiniuData.fileList.push({
            name: that.gridInfo.gridName + index,
            url:url
          })
        }) : ''
      }
    },
    methods: {
      getToken(){  //上传之前获取 token
        qnToken({}).then((result) => {
          this.qiniuData.token= result.data
        })
      },
      beforeAvatarUpload: function(file){//重命名和校验
        var fielLocal = file.name.split(".")
        var fielType = "." + fielLocal[fielLocal.length-1]
        var fielLocalName = fielLocal[0]
        this.qiniuData.key = 'ilink'+'_'+new Date().getTime()+fielType
        //this.qiniuData.key = file.name;
        const isJPG = file.type === "image/jpeg";
        const isPNG = file.type === "image/png";
        const isLt20M = file.size / 1024 / 1024 < 20;
        if (!isJPG && !isPNG) {
          this.$message.error("图片只能是 JPG/PNG 格式!")
          return false;
        }
        if (!isLt20M) {
          this.$message.error("图片大小不能超过 20MB!")
          return false;
        }
      },
      handleAvatarSuccess: function(res, file, fileList) {//上传成功
        this.qiniuData.fileList = fileList
      },
      handleRemovePic: function(file, fileList) {//删除成功
        this.qiniuData.fileList = fileList
      },
      handleError: function(res) {
        this.$message({
          message: "上传失败",
          duration: 2000,
          type: "warning"
        })
      },
      handleExceed(files, fileList) {//文件超出个数限制时的钩子
        this.$message.warning(`只能上传一张图片！`)
      },
      // 保存
      saveGridInfo(formName) {
        // 阻止事件冒泡
        event.stopPropagation()
        let that = this
        let type = 1
        let parames = {}
        // 校验表单
        that.$refs[formName].validate((valid) => {
          if(valid) {
            var parames = {
              gridName : that.gridBaseInfoForm.gridName,
              picUrl: util.ilinkArrHandle.getqiniuPicUrlArr(that.qiniuData.fileList).toString(),
              belongType : 1,
              belongId : that.gridBaseInfoForm.belongId,
              gridmanCount: that.gridBaseInfoForm.gridmanCount,
              chargeGridman: that.gridBaseInfoForm.chargeGridman,
              chargeTel: that.gridBaseInfoForm.chargeTel,
              id: that.gridInfo.id
            }
            // 调用保存接口
            updateGridInfo(parames).then(res => {
              if(res.status === 200) {
                that.$message({
                  message: '保存成功！',
                  type: 'success'
                })
                // 关闭弹框
                that.closeFun(true)
              } else {
                that.$message({
                  message: '保存失败！',
                  type: 'warning'
                })
              }
            })
          } else {
            return false
          }
        })
      },
      selectAreaList(selVal){
        this.gridBaseInfoForm.belongId = selVal
      },
      // 关闭编辑弹框
      closeUploadImage() {
        let that = this
        that.dialogUploadImage = false
      },
    }
  }
</script>
